﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class VertexAnimation : MonoBehaviour {
	float _speed = 1;
	public string defaultAnimName;

	VertexAnimationData meshClip;
	VertexAnimationClip currentPlay;
	Mesh mesh;
	float _cachedPlayTime;
	int frame = 1;

	public bool showPlayAni;
	public static VertexAnimation Get(string name){
		GameObject newobj = new GameObject (name);
		VertexAnimation anim = newobj.AddComponent<VertexAnimation> ();
		return anim;
	}
	// Use this for initialization
	void Awake () {
		meshClip = VertexAnimationMgr.Instance.GetClip (gameObject.name);
		MeshFilter mf = gameObject.AddComponent<MeshFilter> ();
		MeshRenderer mr = gameObject.AddComponent<MeshRenderer> ();

		mr.material = meshClip.material;
		mesh = meshClip.CreateMesh ();
		mf.mesh = mesh;
		if (defaultAnimName == null || defaultAnimName == "") {
			if (meshClip.animationClips.Count == 0) {
				Debug.LogError ("! vanimation has not clips");
				GameObject.Destroy (gameObject);
			}
			defaultAnimName = meshClip.animationClips [0].name;
		}
		Play (defaultAnimName);
	}
	public float GetClipLength(string clipName){
		return meshClip.GetClipLength(clipName);
	}
	public bool IsPlaying(string animname){
		return currentPlay.name == animname;
	}
	public void Play(string name){
		if (meshClip == null)
			Debug.LogError ("meshClip == null");
		if (!meshClip.dictClips.ContainsKey (name)) {
//			Debug.LogWarning (" !!!! can not find the clip named : " + name);
			return;
		}
		currentPlay = meshClip.dictClips [name];
		_cachedPlayTime = Time.time;
	}
//	public void Play(string name,float speed){
//		_speed = speed;
//		currentPlay = meshClip.dictClips [name];
//		_cachedPlayTime = Time.time;
//	}
	public float speed{
		get{return _speed;}
		set{ _speed = value;}
	}
	// Update is called once per frame
	void Update () {
		if (mesh != null && currentPlay != null) {
			if(Time.frameCount % frame == 0)
				currentPlay.BackMesh (ref mesh, (Time.time - _cachedPlayTime) * _speed);
		}
		#if UNITY_EDITOR
		if (showPlayAni) {
			for (int i = 0; i < meshClip.animationClips.Count; i++) {
				if (Input.GetKeyDown(i.ToString())) {
					Play (meshClip.animationClips [i].name);
				}
			}
		}
		#endif
	}
}
